<!DOCTYPE html>
<html lang="cn">
<head>
  <meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=2">
<meta name="theme-color" content="#222">
<meta name="generator" content="Hexo 5.1.1">
  <link rel="apple-touch-icon" sizes="180x180" href="/images/apple-touch-icon-next.png">
  <link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32-next.png">
  <link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16-next.png">
  <link rel="mask-icon" href="/images/logo.svg" color="#222">

<link rel="stylesheet" href="/css/main.css">


<link rel="stylesheet" href="/lib/font-awesome/css/all.min.css">

<script id="hexo-configurations">
    var NexT = window.NexT || {};
    var CONFIG = {"hostname":"example.com","root":"/","scheme":"Gemini","version":"7.8.0","exturl":false,"sidebar":{"position":"left","display":"post","padding":18,"offset":12,"onmobile":false},"copycode":{"enable":false,"show_result":false,"style":null},"back2top":{"enable":true,"sidebar":false,"scrollpercent":false},"bookmark":{"enable":false,"color":"#222","save":"auto"},"fancybox":false,"mediumzoom":false,"lazyload":false,"pangu":false,"comments":{"style":"tabs","active":null,"storage":true,"lazyload":false,"nav":null},"algolia":{"hits":{"per_page":10},"labels":{"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}},"localsearch":{"enable":false,"trigger":"auto","top_n_per_article":1,"unescape":false,"preload":false},"motion":{"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}}};
  </script>

  <meta name="description" content="本文推荐一些java中好用的工具类  如统计执行时长的 Guava下的 Stopwatch 类 Bean 与 Map 相互转换的 Apache的BeanUtils  计时相关项目中经常有记录某一操作花费多长时间的需求，如下是最开始的代码，是不是很熟悉？ 123456long start &#x3D; System.currentTimeMillis();&#x2F;&#x2F;do somethingThread.sleep(">
<meta property="og:type" content="article">
<meta property="og:title" content="工具类整理">
<meta property="og:url" content="http://example.com/2020/11/16/06-util-usage-01/index.html">
<meta property="og:site_name" content="小马向前走">
<meta property="og:description" content="本文推荐一些java中好用的工具类  如统计执行时长的 Guava下的 Stopwatch 类 Bean 与 Map 相互转换的 Apache的BeanUtils  计时相关项目中经常有记录某一操作花费多长时间的需求，如下是最开始的代码，是不是很熟悉？ 123456long start &#x3D; System.currentTimeMillis();&#x2F;&#x2F;do somethingThread.sleep(">
<meta property="og:locale">
<meta property="og:image" content="http://example.com/2020/11/16/06-util-usage-01/qrcode-12cm.jpg">
<meta property="article:published_time" content="2020-11-15T16:00:00.000Z">
<meta property="article:modified_time" content="2021-05-22T08:39:52.000Z">
<meta property="article:author" content="maning">
<meta property="article:tag" content="java">
<meta property="article:tag" content="工具类">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="http://example.com/2020/11/16/06-util-usage-01/qrcode-12cm.jpg">

<link rel="canonical" href="http://example.com/2020/11/16/06-util-usage-01/">


<script id="page-configurations">
  // https://hexo.io/docs/variables.html
  CONFIG.page = {
    sidebar: "",
    isHome : false,
    isPost : true,
    lang   : 'cn'
  };
</script>

  <title>工具类整理 | 小马向前走</title>
  






  <noscript>
  <style>
  .use-motion .brand,
  .use-motion .menu-item,
  .sidebar-inner,
  .use-motion .post-block,
  .use-motion .pagination,
  .use-motion .comments,
  .use-motion .post-header,
  .use-motion .post-body,
  .use-motion .collection-header { opacity: initial; }

  .use-motion .site-title,
  .use-motion .site-subtitle {
    opacity: initial;
    top: initial;
  }

  .use-motion .logo-line-before i { left: initial; }
  .use-motion .logo-line-after i { right: initial; }
  </style>
</noscript>

</head>

<body itemscope itemtype="http://schema.org/WebPage">
  <div class="container use-motion">
    <div class="headband"></div>

    <header class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-container">
  <div class="site-nav-toggle">
    <div class="toggle" aria-label="Toggle navigation bar">
      <span class="toggle-line toggle-line-first"></span>
      <span class="toggle-line toggle-line-middle"></span>
      <span class="toggle-line toggle-line-last"></span>
    </div>
  </div>

  <div class="site-meta">

    <a href="/" class="brand" rel="start">
      <span class="logo-line-before"><i></i></span>
      <h1 class="site-title">小马向前走</h1>
      <span class="logo-line-after"><i></i></span>
    </a>
  </div>

  <div class="site-nav-right">
    <div class="toggle popup-trigger">
    </div>
  </div>
</div>




<nav class="site-nav">
  <ul id="menu" class="main-menu menu">
        <li class="menu-item menu-item-home">

    <a href="/" rel="section"><i class="fa fa-home fa-fw"></i>Home</a>

  </li>
        <li class="menu-item menu-item-about">

    <a href="/about/" rel="section"><i class="fa fa-user fa-fw"></i>About</a>

  </li>
        <li class="menu-item menu-item-tags">

    <a href="/tags/" rel="section"><i class="fa fa-tags fa-fw"></i>Tags</a>

  </li>
        <li class="menu-item menu-item-categories">

    <a href="/categories/" rel="section"><i class="fa fa-th fa-fw"></i>Categories</a>

  </li>
        <li class="menu-item menu-item-archives">

    <a href="/archives/" rel="section"><i class="fa fa-archive fa-fw"></i>Archives</a>

  </li>
  </ul>
</nav>




</div>
    </header>

    
  <div class="back-to-top">
    <i class="fa fa-arrow-up"></i>
    <span>0%</span>
  </div>


    <main class="main">
      <div class="main-inner">
        <div class="content-wrap">
          

          <div class="content post posts-expand">
            

    
  
  
  <article itemscope itemtype="http://schema.org/Article" class="post-block" lang="cn">
    <link itemprop="mainEntityOfPage" href="http://example.com/2020/11/16/06-util-usage-01/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="image" content="/images/avatar.gif">
      <meta itemprop="name" content="maning">
      <meta itemprop="description" content="小马向前走">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="小马向前走">
    </span>
      <header class="post-header">
        <h1 class="post-title" itemprop="name headline">
          工具类整理
        </h1>

        <div class="post-meta">
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-calendar"></i>
              </span>
              <span class="post-meta-item-text">Posted on</span>

              <time title="Created: 2020-11-16 00:00:00" itemprop="dateCreated datePublished" datetime="2020-11-16T00:00:00+08:00">2020-11-16</time>
            </span>
              <span class="post-meta-item">
                <span class="post-meta-item-icon">
                  <i class="far fa-calendar-check"></i>
                </span>
                <span class="post-meta-item-text">Edited on</span>
                <time title="Modified: 2021-05-22 16:39:52" itemprop="dateModified" datetime="2021-05-22T16:39:52+08:00">2021-05-22</time>
              </span>
            <span class="post-meta-item">
              <span class="post-meta-item-icon">
                <i class="far fa-folder"></i>
              </span>
              <span class="post-meta-item-text">In</span>
                <span itemprop="about" itemscope itemtype="http://schema.org/Thing">
                  <a href="/categories/java/" itemprop="url" rel="index"><span itemprop="name">java</span></a>
                </span>
            </span>

          

        </div>
      </header>

    
    
    
    <div class="post-body" itemprop="articleBody">

      
        <p>本文推荐一些java中好用的工具类</p>
<ol>
<li>如统计执行时长的 Guava下的 Stopwatch 类</li>
<li>Bean 与 Map 相互转换的 Apache的BeanUtils</li>
</ol>
<h1 id="计时相关"><a href="#计时相关" class="headerlink" title="计时相关"></a>计时相关</h1><p>项目中经常有记录某一操作花费多长时间的需求，如下是最开始的代码，是不是很熟悉？</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br></pre></td><td class="code"><pre><span class="line"><span class="keyword">long</span> start = System.currentTimeMillis();</span><br><span class="line"><span class="comment">//do something</span></span><br><span class="line">Thread.sleep(<span class="number">2020</span>);</span><br><span class="line"></span><br><span class="line"><span class="keyword">long</span> end = System.currentTimeMillis();</span><br><span class="line">System.out.println(<span class="string">&quot;运行时间：&quot;</span>+(end - start)+ <span class="string">&quot;ms&quot;</span>);</span><br></pre></td></tr></table></figure>

<p>这种方式确实简单，但是这种方式也有不灵活的地方</p>
<ol>
<li>默认情况下我们只能取ms为单位，如果需要分钟，则需要自己换算单位。</li>
<li>不能支持更复杂的计时需求，如中途暂停计时，当代码执行到某一步再继续计时。</li>
</ol>
<p><strong>下面介绍一个关于计时的工具类 Guava下的 Stopwatch</strong></p>
<p>引入依赖</p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>com.google.guava<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>guava<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>23.5-jre<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p>Stopwatch代码示例</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><span class="line"><span class="meta">@Test</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">void</span> <span class="title">stopwatch1</span><span class="params">()</span> <span class="keyword">throws</span> InterruptedException </span>&#123;</span><br><span class="line">    <span class="comment">//创建stopwatch并开始计时</span></span><br><span class="line">    Stopwatch stopwatch=Stopwatch.createStarted();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    Thread.sleep(<span class="number">2020</span>);</span><br><span class="line">    System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS));</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//暂停计时</span></span><br><span class="line">    stopwatch.stop();</span><br><span class="line">    Thread.sleep(<span class="number">1000</span>);</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//再次开始计时</span></span><br><span class="line">    stopwatch.start();</span><br><span class="line">    Thread.sleep(<span class="number">2020</span>);</span><br><span class="line">    stopwatch.stop();</span><br><span class="line"></span><br><span class="line"></span><br><span class="line">    <span class="comment">//统计运行时长</span></span><br><span class="line">    System.out.println(stopwatch.elapsed(TimeUnit.MILLISECONDS));</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>

<p>可以看到除了满足基本的计时需求外，其使用更灵活，更简单。 </p>
<ol>
<li><p>不需要自己再去计算时长</p>
</li>
<li><p>可以中途暂停计时</p>
</li>
</ol>
<p>下面总结下常用的操作</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">//创建计时器,但是不立即运行 需要主动调用 stopwatch.start()方法开始计时</span></span><br><span class="line">Stopwatch stopwatch=Stopwatch.createUnstarted();</span><br><span class="line">stopwatch.start();</span><br><span class="line"></span><br><span class="line"><span class="comment">//创建stopwatch并开始计时</span></span><br><span class="line"> Stopwatch stopwatch=Stopwatch.createStarted();</span><br><span class="line"></span><br><span class="line"><span class="comment">//暂停计时</span></span><br><span class="line">stopwatch.stop();</span><br><span class="line"></span><br><span class="line"><span class="comment">//统计运行时长</span></span><br><span class="line">stopwatch.elapsed(TimeUnit.MILLISECONDS)</span><br></pre></td></tr></table></figure>



<h1 id="Bean-与-Map-互转"><a href="#Bean-与-Map-互转" class="headerlink" title="Bean 与 Map 互转"></a>Bean 与 Map 互转</h1><p>日常开发中经常有将Bean转成Map,或者将Map转成Bean的需求,这里阐述下具体的实现.</p>
<p>目前Map 与 Bean互转有如下几种方式</p>
<ol>
<li>方式一: 通过Jackson 先将Bean转成json,再将json转成Map</li>
<li>方式二: 使用Spring的BeanMap类</li>
<li>方式三: 使用Apache的BeanUtils</li>
</ol>
<p>我目前使用方式三. 原因如下</p>
<ol>
<li>方式一 效率不行</li>
<li>方式二 需要依赖spring,在有些非spring系工程中不方便使用</li>
</ol>
<p><strong>使用Apache的BeanUtils</strong></p>
<p><strong>引入依赖</strong></p>
<figure class="highlight xml"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line"><span class="tag">&lt;<span class="name">dependency</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">groupId</span>&gt;</span>commons-beanutils<span class="tag">&lt;/<span class="name">groupId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">artifactId</span>&gt;</span>commons-beanutils<span class="tag">&lt;/<span class="name">artifactId</span>&gt;</span></span><br><span class="line">    <span class="tag">&lt;<span class="name">version</span>&gt;</span>1.9.4<span class="tag">&lt;/<span class="name">version</span>&gt;</span></span><br><span class="line"><span class="tag">&lt;/<span class="name">dependency</span>&gt;</span></span><br></pre></td></tr></table></figure>



<p><strong>bean 转 map</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * bean 转 map</span></span><br><span class="line"><span class="comment"> * */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Map <span class="title">beanToMap</span><span class="params">(Object bean)</span></span>&#123;</span><br><span class="line">    Map&lt;String,String&gt; map=Maps.newHashMap();</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        map=BeanUtils.describe(bean);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> map;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>



<p><strong>map 转 bean</strong></p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br></pre></td><td class="code"><pre><span class="line"><span class="comment">/**</span></span><br><span class="line"><span class="comment"> * map 转 bean</span></span><br><span class="line"><span class="comment"> * */</span></span><br><span class="line"><span class="function"><span class="keyword">public</span> <span class="keyword">static</span> Object <span class="title">mapToBean</span><span class="params">(Map map,Object bean)</span></span>&#123;</span><br><span class="line">    <span class="keyword">try</span> &#123;</span><br><span class="line">        BeanUtils.populate(bean,map);</span><br><span class="line">    &#125; <span class="keyword">catch</span> (Exception e) &#123;</span><br><span class="line">        e.printStackTrace();</span><br><span class="line">    &#125;</span><br><span class="line">    <span class="keyword">return</span> bean;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure>







<hr>
<p>微信端的朋友也可关注我的公众号</p>
<p><strong>小马向前走</strong></p>
<p><img src="/2020/11/16/06-util-usage-01/qrcode-12cm.jpg" alt="qrcode-12cm"></p>

    </div>

    
    
    

      <footer class="post-footer">
          <div class="post-tags">
              <a href="/tags/java/" rel="tag"># java</a>
              <a href="/tags/%E5%B7%A5%E5%85%B7%E7%B1%BB/" rel="tag"># 工具类</a>
          </div>

        


        
    <div class="post-nav">
      <div class="post-nav-item">
    <a href="/2020/10/26/04-st4-usage/" rel="prev" title="st4 字符串模板引擎的使用">
      <i class="fa fa-chevron-left"></i> st4 字符串模板引擎的使用
    </a></div>
      <div class="post-nav-item">
    <a href="/2021/02/08/07-rest-template/" rel="next" title="RestTemplate在非springboot工程中的使用">
      RestTemplate在非springboot工程中的使用 <i class="fa fa-chevron-right"></i>
    </a></div>
    </div>
      </footer>
    
  </article>
  
  
  



          </div>
          

<script>
  window.addEventListener('tabs:register', () => {
    let { activeClass } = CONFIG.comments;
    if (CONFIG.comments.storage) {
      activeClass = localStorage.getItem('comments_active') || activeClass;
    }
    if (activeClass) {
      let activeTab = document.querySelector(`a[href="#comment-${activeClass}"]`);
      if (activeTab) {
        activeTab.click();
      }
    }
  });
  if (CONFIG.comments.storage) {
    window.addEventListener('tabs:click', event => {
      if (!event.target.matches('.tabs-comment .tab-content .tab-pane')) return;
      let commentClass = event.target.classList[1];
      localStorage.setItem('comments_active', commentClass);
    });
  }
</script>

        </div>
          
  
  <div class="toggle sidebar-toggle">
    <span class="toggle-line toggle-line-first"></span>
    <span class="toggle-line toggle-line-middle"></span>
    <span class="toggle-line toggle-line-last"></span>
  </div>

  <aside class="sidebar">
    <div class="sidebar-inner">

      <ul class="sidebar-nav motion-element">
        <li class="sidebar-nav-toc">
          Table of Contents
        </li>
        <li class="sidebar-nav-overview">
          Overview
        </li>
      </ul>

      <!--noindex-->
      <div class="post-toc-wrap sidebar-panel">
          <div class="post-toc motion-element"><ol class="nav"><li class="nav-item nav-level-1"><a class="nav-link" href="#%E8%AE%A1%E6%97%B6%E7%9B%B8%E5%85%B3"><span class="nav-number">1.</span> <span class="nav-text">计时相关</span></a></li><li class="nav-item nav-level-1"><a class="nav-link" href="#Bean-%E4%B8%8E-Map-%E4%BA%92%E8%BD%AC"><span class="nav-number">2.</span> <span class="nav-text">Bean 与 Map 互转</span></a></li></ol></div>
      </div>
      <!--/noindex-->

      <div class="site-overview-wrap sidebar-panel">
        <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
  <p class="site-author-name" itemprop="name">maning</p>
  <div class="site-description" itemprop="description">小马向前走</div>
</div>
<div class="site-state-wrap motion-element">
  <nav class="site-state">
      <div class="site-state-item site-state-posts">
          <a href="/archives/">
        
          <span class="site-state-item-count">18</span>
          <span class="site-state-item-name">posts</span>
        </a>
      </div>
      <div class="site-state-item site-state-categories">
            <a href="/categories/">
          
        <span class="site-state-item-count">4</span>
        <span class="site-state-item-name">categories</span></a>
      </div>
      <div class="site-state-item site-state-tags">
            <a href="/tags/">
          
        <span class="site-state-item-count">14</span>
        <span class="site-state-item-name">tags</span></a>
      </div>
  </nav>
</div>



      </div>

    </div>
  </aside>
  <div id="sidebar-dimmer"></div>


      </div>
    </main>

    <footer class="footer">
      <div class="footer-inner">
        

        

<div class="copyright">
  
  &copy; 
  <span itemprop="copyrightYear">2025</span>
  <span class="with-love">
    <i class="fa fa-heart"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">maning</span>
</div>
  <div class="powered-by">Powered by <a href="https://hexo.io/" class="theme-link" rel="noopener" target="_blank">Hexo</a> & <a href="https://theme-next.org/" class="theme-link" rel="noopener" target="_blank">NexT.Gemini</a>
  </div>

        








      </div>
    </footer>
  </div>

  
  <script src="/lib/anime.min.js"></script>
  <script src="/lib/velocity/velocity.min.js"></script>
  <script src="/lib/velocity/velocity.ui.min.js"></script>

<script src="/js/utils.js"></script>

<script src="/js/motion.js"></script>


<script src="/js/schemes/pisces.js"></script>


<script src="/js/next-boot.js"></script>




  















  

  

</body>
</html>
